package com.example.jianbing.juc;

import org.springframework.aop.scope.ScopedProxyUtils;

import java.util.concurrent.*;

/**
 * @ClassName : MyThreadPoolDemo
 * @Description :
 * @Author : JB
 * @Date: 2020-08-08 01:31
 */

/***
 *工作线程数+阻塞队列 =  ThreadPoolExecutor
 * 七个重要参数
 *      int corePoolSize,      线程池中常驻核心线程数
 *      int maximumPoolSize,    线程池能够容纳同时执行的最大线程数，此值必须>=1
 *      long keepAliveTime,     多余线程的存活时间（当前池中线程数量超过corePoolSize，当空闲时间达到keepAliveTime，多余的线程会被销毁直到只剩下corePoolSize个线程为止）
 *      TimeUnit unit,          keepAliveTime的单位
 *      BlockingQueue<Runnable> workQueue,   任务队列，被提交尚未被执行的任务
 *      ThreadFactory threadFactory,        表示生成的线程池中工作线程的线程工厂，同于创建线程，一般默认的即可
 *      RejectedExecutionHandler handler    拒绝策略，表示队列满了，如何来拒绝请求执行的runnable策略
 *
 *
 */
public class MyThreadPoolDemo {
    public static void main(String[] args) {
        //System.out.println(Runtime.getRuntime().availableProcessors());
       ExecutorService threadPool = new ThreadPoolExecutor(
               2,
               5,
               2L,
               TimeUnit.MINUTES,
               new LinkedBlockingQueue<>(3),
               Executors.defaultThreadFactory(),
               new ThreadPoolExecutor.CallerRunsPolicy()
       );

        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t办理业务");
                });
               // TimeUnit.SECONDS.sleep(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
    public static  void initPool(){
        //ExecutorService threadPool = Executors.newFixedThreadPool(5);
        //ExecutorService threadPool = Executors.newSingleThreadExecutor();
        ExecutorService threadPool = Executors.newCachedThreadPool();
        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t办理业务");
                });
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
}
